/*
 * This file (AxFileChooserFilter.java) is protected by the GNU GPL licence (v2). 
 * Please read the license.txt attached for further informations. 
 * 
 */

package artx.gui;

import java.io.File;
import java.util.ArrayList;

import javax.swing.filechooser.FileFilter;

/**
 * Generic filter class using a list of string extension to build a File Chooser
 * Filter.
 * 
 * @author Xavier Gouchet
 * 
 */
public class AxFileChooserFilter extends FileFilter {

	private String description;

	private ArrayList<String> extensions;

	/**
	 * Standard constructor.
	 * 
	 * @param desc
	 *            description of the filter (ex : "Images (*.png;*.tga;*.jpg)")
	 * @param list
	 *            list of correct extensions without the ".", all in lowercase
	 *            (ex : {"png","tga","*"})
	 */
	public AxFileChooserFilter(String desc, ArrayList<String> list) {
		if ((desc != null) && (!desc.isEmpty())) {
			this.description = new String(desc);
		} else {
			this.description = "???";
		}
		if (list != null) {
			this.extensions = list;
		} else {
			this.extensions = null;
		}
	}

	/**
	 * @see javax.swing.filechooser.FileFilter#accept(java.io.File)
	 */
	public boolean accept(File f) {
		if (f.isDirectory()) {
			return true;
		}

		String ext = null;
		String s = f.getName();
		int i = s.lastIndexOf('.');
		if (i > 0 && i < s.length() - 1) {
			ext = s.substring(i + 1).toLowerCase();
		}

		if (ext != null) {
			if (this.extensions.contains(ext))
				return true;
		}
		if (this.extensions.contains("*"))
			return true;
		return false;
	}

	/**
	 * @see javax.swing.filechooser.FileFilter#getDescription()
	 */
	public String getDescription() {
		return new String(this.description);
	}

}
